package bar.dark.lee.setting.auto;


import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.cashdrawing.CashDrawingActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.setting.TipInfoActivity;
import bar.dark.lee.setting.TipsActivity;
import bar.dark.lee.setting.auto.AutoActivity.AutoAdapter;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class AutoSelectActivity extends SuperActivity
{
	public static final String AUTO_SELECT_DATA = "auto_select_data";
	
	private static final String IN = "수입";
	private static final String OUT = "지출";
	private static final String BANK = "통장";
	private static final String CREDIT = "신용카드";
	private static final String BANK_KIND = "통장이름";
	private static final String CREDIT_KIND = "카드이름";
	
	private DBSQLite sql;
	
	private TextView inOut;
	private TextView bankCredit;
	private TextView name;
	private TextView date;
	private TextView kind;
	private TextView kindName;
	private TextView category;
	private TextView money;
	private View creditDateView;
	private TextView creditDateTextView;
	private TextView memo;
	
	private Button deleteButton;
	private Button updateButton;
	
	private AutoData data;
	private AutoData newData;
	
	private AutoCreditDateData creditDateData = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		sql = DBSQLite.getInstance(this);
		
		setContentView(R.layout.auto_select_activity);
		
		setTitle("자동화 정보");
		
		Intent intent = getIntent();
		
		data = intent.getParcelableExtra(AutoActivity.AUTO_DATA);
		
		setFindView();
		setOnClickListener();
	}
	
	@Override
	protected void onResume()
	{
		super.onResume();
		new ShowDialog().execute(BDUtil.asyncFlag, 1);
	}

	private void setFindView()
	{
		inOut = (TextView) findViewById(R.id.autoSelectInOut);
		bankCredit = (TextView) findViewById(R.id.autoSelectBankCredit);
		name = (TextView) findViewById(R.id.autoSelectName);
		date = (TextView) findViewById(R.id.autoSelectDate);
		kind = (TextView) findViewById(R.id.autoSelectKind);
		kindName = (TextView) findViewById(R.id.autoSelectKindName);
		category = (TextView) findViewById(R.id.autoSelectCategory);
		money = (TextView) findViewById(R.id.autoSelectMoney);
		creditDateView = findViewById(R.id.autoSelectCreditDateView);
		creditDateTextView = (TextView) findViewById(R.id.autoSelectCreditDateTextView);
		memo = (TextView) findViewById(R.id.autoSelectMemo);
		
		deleteButton = (Button) findViewById(R.id.autoDeleteButton);
		updateButton = (Button) findViewById(R.id.autoUpdateButton);
	}
	
	private void setData()
	{
		sql.selectMapTile(this, "SELECT * FROM auto_bank WHERE id = " + data.getId() + ";", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				newData = null;
				
				int idIdx = c.getColumnIndex("id");
				int nameIdx = c.getColumnIndex("name");
				int categoryIdx = c.getColumnIndex("category");
				int moneyIdx = c.getColumnIndex("money");
				int moneytypeIdx = c.getColumnIndex("moneytype");
				int autodateIdx = c.getColumnIndex("autodate");
				int signdateIdx = c.getColumnIndex("signdate");
				int moneykindIdx = c.getColumnIndex("moneykind");
				int memoIdx = c.getColumnIndex("memo");
				int kindIdx = c.getColumnIndex("kind");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					newData = new AutoData();
					
					newData.setId(c.getInt(idIdx) + "");
					newData.setName(c.getString(nameIdx));
					newData.setCategory(c.getString(categoryIdx));
					newData.setMoney(c.getString(moneyIdx));
					newData.setMoneytype(c.getInt(moneytypeIdx) + "");
					newData.setAutodate(c.getInt(autodateIdx)+ "");
					newData.setSigndate(c.getInt(signdateIdx)+ "");
					newData.setMoneykind(c.getString(moneykindIdx));
					newData.setMemo(c.getString(memoIdx));
					newData.setKind(c.getInt(kindIdx) + "");
					c.moveToNext();
				}
			}
		});
		
		if (newData.getKind().equals("1"))
		{
			return;
		}
		
		sql.selectMapTile(this, "SELECT * FROM auto_credit_date WHERE linkid ="
				+ newData.getId() + ";", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int idIdx = c.getColumnIndex("id");
				int nameIdx = c.getColumnIndex("name");
				int monthcountIdx = c.getColumnIndex("monthcount");
				int signcountIdx = c.getColumnIndex("signcount");
				int linkidIdx = c.getColumnIndex("linkid");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					creditDateData = new AutoCreditDateData();
					
					creditDateData.setId(c.getInt(idIdx) + "");
					creditDateData.setName(c.getString(nameIdx));
					creditDateData.setMonthcount(c.getInt(monthcountIdx) + "");
					creditDateData.setSigncount(c.getInt(signcountIdx) + "");
					creditDateData.setLinkid(c.getInt(linkidIdx) + "");
					
					c.moveToNext();
				}
			}
		});
	}
	
	private void setOnClickListener()
	{
		deleteButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				new ShowDialog().execute(BDUtil.asyncFlag, 2);
			}
		});
		
		updateButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(AutoSelectActivity.this, AutoInsertActivity.class);
				intent.putExtra(AutoActivity.AUTO_UPDATE_DELECT_FLAG, AutoActivity.AUTO_UPDATE);
				intent.putExtra(AUTO_SELECT_DATA, data);
				startActivity(intent);
			}
		});
	}
	
	private void setDeleteData()
	{
		String [] whereArgs = new String[]{data.getId()};
		
		sql.delete(this, "auto_bank", "id = ?", whereArgs);
	}
	
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (BDUtil.btnEnable)
			{
				BDUtil.btnEnable = false;
				BDUtil.asyncFlag = -1;
				
				dialog = new ProgressDialog(AutoSelectActivity.this);
				dialog.setCancelable(false);
				dialog.setMessage("Loading...");
				dialog.show();
			}
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			
			if (arg0[0] == 0) {
				if (arg0[1] == 1)
				{
					setData();
					
					return arg0[1];
				}
				else if (arg0[1] == 2)
				{
					try
					{
						sql.beginTansaction(superContext);
						
						setDeleteData();
						
						sql.setTransactionSuccessful();
					} catch (Exception e)
					{
						return -1;
					} finally {
						try 
						{
							sql.endTransaction(superContext);
						} catch (Exception e) 
						{
							return -1;
						}
					}
					
					return arg0[1];
				}
				return arg0[0];
			} else 
				return arg0[0];
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			
			if (dialog != null) {
				dialog.dismiss();
			}
			
			if (result == -1)
			{
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
				
				BDUtil.showDialog(superContext, "오류", "데이터 저장에 실패했습니다.");
			}
			else if (result == 1)
			{
				if (newData != null)
				{
					if (newData.getMoneytype().equals("1"))
					{
						inOut.setText(OUT);
					}
					else 
					{
						inOut.setText(IN);
					}
					
					if (newData.getKind().equals("1"))
					{
						bankCredit.setText(BANK);
						kind.setText(BANK_KIND);
					}
					else
					{
						bankCredit.setText(CREDIT);
						kind.setText(CREDIT_KIND);
					}
					
					name.setText(newData.getName());
					date.setText("매월 " + newData.getAutodate() + " 일");
					kindName.setText(newData.getMoneykind());
					category.setText(newData.getCategory());
					money.setText(BDUtil.getWon(newData.getMoney()) + shape);
					memo.setText(newData.getMemo());
					
					if (newData.getKind().equals("2"))
					{
						creditDateView.setVisibility(View.VISIBLE);
						
						if (creditDateData == null)
						{
							creditDateTextView.setText(AutoInsertActivity.ALL);
						}
						else
						{
							creditDateTextView.setText(creditDateData.getMonthcount());
						}
					}
					else
					{
						creditDateView.setVisibility(View.GONE);
					}
				}
				
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
			}
			else if (result == 2)
			{
				BDUtil.showDialogFinish(AutoSelectActivity.this, "알림", 
						"자동이체 데이터 " + data.getName() + "가 삭제 되었습니다.");
			}
		}
	}

	@Override
	protected void tipButton()
	{
		Intent intent = new Intent(AutoSelectActivity.this, TipInfoActivity.class);
		intent.putExtra(TipsActivity.TIP_REQUEST_KEY, TipsActivity.TIP_AUTOBANK);
		startActivity(intent);
	}
}
